import Vue from "vue";
import Router from "vue-router";

// 解决 vue-router 3.1.0+路由，重新进入相同路由时报错的问题 Uncaught(in Promise)
const VueRouterPush = Router.prototype.push;
Router.prototype.push = function push(toLocation) {
  return VueRouterPush.call(this, toLocation).catch((err) => err);
};

Vue.use(Router);

let routes = [];

const routerContext = require.context("./", true, /index\.js/);
routerContext.keys().forEach((route) => {
  // 如果是根目录的index.js，不处理
  if (route.startsWith("./index")) {
    return;
  }
  const routerModule = routerContext(route);
  /**
   * 兼容 import export 和 require module.export 两种规范
   */
  routes = [...routes, ...(routerModule.default || routerModule)];
});

const routers = new Router({
  // mode: 'history', //后端支持可开
  routes: routes,
});

// routers.addRoutes([{ path: '*', name: '404', redirect: '/404' }])

function getToken() {
  let retToken = sessionStorage.getItem("userInfo");
  return retToken;
}

routers.beforeEach((to, from, next) => {
  // todo 切勿提交
  getToken()
  next();
  /*if (getToken() || to.meta.nonAuth) {
    // 已获取到token或者不需要token校验
    next();
  } else {
    // 否则重定向到登录页
    if (to.path === "/error") next();
    else next("/error");
  }*/
});

export default routers;
